//
//  UIColorExtension.m
//  zhankooApp
//
//  Created by Jervis on 14/11/4.
//  Copyright (c) 2014年 zhankoo. All rights reserved.
//

#import "UIColorExtension.h"

@implementation UIColor (UIColorExtension)

+ (UIColor *) colorWithHexString: (NSString *)color
{
    return [UIColor colorWithHexString: color alpha: 1.0f];
}

+ (UIColor *) colorWithHexString: (NSString *)color alpha: (float)alpha
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    
    if (cString.length != 6) {
        return [UIColor blackColor];
    }
    
    NSRange range;
    range.length = 2;
    
    //red
    range.location = 0;
    NSString *red = [cString substringWithRange: range];
    
    //green
    range.location = 2;
    NSString *green = [cString substringWithRange: range];
    
    //blue
    range.location = 4;
    NSString *blue = [cString substringWithRange: range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString: red] scanHexInt: &r];
    [[NSScanner scannerWithString: green] scanHexInt: &g];
    [[NSScanner scannerWithString: blue] scanHexInt: &b];
    
    return [UIColor colorWithRed: (float)r / 255.0 green: (float)g / 255.0 blue: (float)b / 255.0 alpha: alpha];
}

@end
